package com.ctl.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
public class TokenGlobalFilter implements GlobalFilter, Ordered {
    @Autowired
    private RedisTemplate redisTemplate;

    @Override

    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

//        拦截了所有请求。 进行强制登录判断，去登录的请求这个不应该判断
        RequestPath path = request.getPath();
        System.out.println("path: "+path);

        if(!path.toString().equals("/bzkt-admin/tokens")){
//            本次请求不是登录
            List<String> token = request.getQueryParams().get("token");
            if(token == null){
                throw new RuntimeException("没有登录，无权访问");
            }

//            判断redis中是否存在
            String tk = token.get(0);
            if(!redisTemplate.hasKey(tk)){
                throw new RuntimeException("你的登录令牌以失效");
            }
        }

        return chain.filter(exchange);
    }

    public int getOrder() {
        return -1;
    }
}
